﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data;

namespace YTSK.Vouch
{
    public class VouchInit
    {
        public VouchInitGridInventory _dg;
        public DataGridView _dgsum;
        public List<Model.Voucher> _vouchs;
        public Dictionary<string, object> _controlValue;
        public int _idwarehouse;
        public string _cvoutype;
        public Control _main;
        public bool _bControlHandle = false;

        #region 客户档案参照
        VouchInitTbCustomer customerhandle;
        #endregion

        public bool bControlHandle
        {
            set { _bControlHandle = value; if (value) { EnableHandle(); } else { DisableHandle(); } }
            get { return _bControlHandle; }
        }

        public VouchInit(string cvouchtype,Control c)
        {
            _cvoutype = cvouchtype;
            _main = c;
            _dg = new VouchInitGridInventory();
            _dgsum = new DataGridView();
    }

        #region 初始化单据
        /// <summary>
        /// 格式化单据
        /// </summary>
        /// <param name="main"></param>
        /// <param name="vouchercode"></param>
        public virtual void Init()
        {
            GetDataFromVouch();
            var heads = _vouchs.Where(x => x.iHead == 1).ToList();
            VouchHead(heads, _main, _controlValue);
            var tmpgird = _vouchs.FirstOrDefault(x => x.iHead == 2 && x.FieldCode == "dataGrid");
            var dggrids = _vouchs.Where(x => x.iHead == 2 && x.FieldCode != "dataGrid")
                .OrderBy(x => x.iOrder).ToList();
            DataGrid(_main, tmpgird, dggrids);
            AddHandle();

        }
        #endregion

        public void SetDefaultWarehouse()
        {
            #region 设置默认仓库
            var warehouse = _main.Controls.Find("IDWarehouse", true);
            if (warehouse.Count() > 0)
            {
                var combo = (ComboBox)warehouse[0];
                var cwhcode = cSK.cSKSet.loadsave(SkConfig.默认仓库);
                if (cwhcode.Length > 0)
                {
                    for (int k = 0; k < combo.Items.Count; k++)
                    {
                        var item = combo.Items[k];
                        var dtr = (DataRowView)item;
                        if (dtr["value"].ObjToString().IndexOf(cwhcode) >= 0)
                        { combo.SelectedIndex = k; break; }
                    }
                }
            }
            #endregion
        }

        #region 获取格式化的数据
        /// <summary>
        /// 获取格式化的数据
        /// </summary>
        /// <param name="vouchercode"></param>
        private void GetDataFromVouch()
        {
            #region 获取格式化数据
            var url = string.Format("{0}/api/oms/Voucher/GetOne?token={1}&VoucherCode={2}",
                ServerConfig.ServerAddress, ServerConfig.GetToken(), _cvoutype);
            var s = Common.handleHttp.Get(url);
            var result = Common.handleJSON.DeserializeResult(s);
            if (result.result != 1)
            { throw new Exception(result.resultdetail); }
            _vouchs = result.GetList<Model.Voucher>("Vouchers");
            _controlValue = (Dictionary<string, object>)result.GetVal("ControlValue");
            #endregion
        }

        #endregion       

        #region 初始化单据头
        private void VouchHead(List<Model.Voucher> heads,Control main, Dictionary<string,object> controlValue)
        {
            #region 格式化表头
            for (int i = 0; i < heads.Count; i++)
            {
                var t = heads[i];
                var label = new Label();
                label.Top = t.iTop.ObjToInt() + 5;
                label.Height = t.iHeight.ObjToInt() - t.iTop.ObjToInt();
                label.Left = t.iLeft;
                label.Text = t.FieldTitle;
                label.Visible = true;
                label.Name = "label_" + t.FieldCode;
                label.AutoSize = true;
                main.Controls.Add(label);
                var ileft = t.iLeft + label.Width;
                switch (t.ControlType)
                {
                    case "date":
                        main.Controls.Add(InitDate(t, ileft));
                        break;
                    case "select":
                        System.Collections.ArrayList ar;
                        if (controlValue.Keys.Contains(t.FieldCode))
                        { ar= (System.Collections.ArrayList)controlValue[t.FieldCode]; }
                        else { ar = null; }
                        main.Controls.Add(InitCombo(t, ileft, ar));
                        break;
                    default:
                        main.Controls.Add(InitTextBox(t, ileft));
                        break;
                }
            }
            #endregion
        }

        #region 单据头的控件
        #region 初始化控件textBox
        private TextBox InitTextBox(Model.Voucher t, int ileft)
        {
            var c = new TextBox();
            c.Top = t.iTop.ObjToInt();
            c.Height = t.iHeight.ObjToInt() - t.iTop.ObjToInt();
            c.Left = ileft;
            c.Name = t.FieldCode;
            c.Width = t.iWidth.ObjToInt() - ileft;
            c.Text = t.cDefaultValue;
            c.Visible = true;
            if (t.bModify.ObjToInt() == 0)
            { c.ReadOnly =true; }
            return c;
        }
        #endregion

        #region 初始化控件Date
        private DateTimePicker InitDate(Model.Voucher t, int ileft)
        {
            var c = new DateTimePicker();
            c.Top = t.iTop.ObjToInt();
            c.Height = t.iHeight.ObjToInt() - t.iTop.ObjToInt();
            c.Left = ileft;
            c.Name = t.FieldCode;
            c.Width = t.iWidth.ObjToInt() - ileft;
            if (t.cDefaultValue.ObjToString().Length > 0)
            { c.Value = t.cDefaultValue.ObjToDate(); }
            c.Visible = true;
            if (t.bModify.ObjToInt() == 0)
            { c.Enabled = false; }
            return c;
        }
        #endregion

        #region 初始化控件ComboBox
        private ComboBox InitCombo(Model.Voucher t, int ileft, System.Collections.ArrayList value)
        {
            var c = new ComboBox();
            if (value == null)
            { c.DropDownStyle = ComboBoxStyle.DropDown; }
            else { c.DropDownStyle = ComboBoxStyle.DropDownList; }
            c.Top = t.iTop.ObjToInt();
            c.Height = t.iHeight.ObjToInt() - t.iTop.ObjToInt();
            c.Left = ileft;
            c.Name = t.FieldCode;
            c.Width = t.iWidth.ObjToInt() - ileft;
            if (value != null)
            {
                var data = new DataTable();
                data.Columns.Add("key");
                data.Columns.Add("value");
                foreach (Dictionary<string, object> v in value)
                {
                    var dtr = data.NewRow();
                    dtr["key"] = v["key"];
                    dtr["value"] = v["value"];
                    //c.Items.Add(dtr);
                    data.Rows.Add(dtr);
                }
                c.DataSource = data;
                c.DisplayMember = "value";
                c.ValueMember = "key";
                c.Visible = true;
                if (t.bModify.ObjToInt() == 0)
                { c.Enabled = false; }                
            }
            //if (t.cDefaultValue != "")
            //{ c.SelectedValue = t.cDefaultValue; }

            return c;
        }
        #endregion
        #endregion

        #endregion


        #region 增加客户档案的下拉框
        private void AddHandle()
        {
            customerhandle = new VouchInitTbCustomer(_main);
            var customer = _main.Controls.Find("cCusName",true);
            if (customer.Count() > 0)
            {
                var tbcus = (TextBox)customer[0];
                customerhandle.AddHandle(tbcus);
            }
        }
        #endregion
        #region 增加客户档案的下拉开启
        private void EnableHandle()
        {
            customerhandle.EnableHandle();
            _dg._datagrideditcontrolhasevents = false;
        }
        #endregion
        #region 增加客户档案的下拉关闭
        private void DisableHandle()
        {
            customerhandle.DisableHandle();
            _dg._datagrideditcontrolhasevents = true;
        }
        #endregion


        #region 初始化表格
        private void DataGrid(Control main, Model.Voucher grid,List<Model.Voucher> dggrids)
        {
            #region 格式化表格
            if (grid != null)
            {
                _dg.Left = grid.iLeft;
                _dg.Width = grid.iWidth.ObjToInt();
                _dg.Top = grid.iTop.ObjToInt();
                _dg.Height = grid.iHeight.ObjToInt() - 50;
                _dg.Visible = true;
                _dg.Name = "dataGrid";
                int itotalwidth = 0;
                for (int i = 0; i < dggrids.Count; i++)
                {
                    var t = dggrids[i];
                    var dgc = new DataGridViewTextBoxColumn();
                    dgc.HeaderText = t.FieldTitle;
                    dgc.Name = t.FieldCode;
                    dgc.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
                    dgc.DataPropertyName = t.FieldCode;
                    dgc.Width = t.iWidth.ObjToInt();
                    dgc.Visible = t.bVisible;
                    dgc.Tag = t.ControlType;
                    dgc.SortMode = DataGridViewColumnSortMode.NotSortable;
                    switch (t.iAlign.ObjToInt())
                    {
                        case 2:
                            dgc.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
                            break;
                        case 3:
                            dgc.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
                            break;
                    }
                    if (t.cFormat.ObjToString().Length > 0)
                    { dgc.DefaultCellStyle.Format = t.cFormat.ObjToString(); }
                    if (t.bModify.ObjToInt() == 0)
                    { dgc.ReadOnly = true; }
                    else { dgc.ReadOnly = false; }
                    //dgc.ReadOnly = false;
                    _dg.Columns.Add(dgc);
                    var dgsumc = new DataGridViewTextBoxColumn();
                    dgsumc.Width = dgc.Width;
                    if (dgc.Visible)
                    { itotalwidth += dgc.Width; }
                    dgsumc.Visible = dgc.Visible;
                    dgsumc.Name = dgc.Name;
                    dgsumc.DataPropertyName = dgc.Name;
                    dgsumc.HeaderText = "";
                    dgsumc.HeaderCell.Style.Alignment = dgc.DefaultCellStyle.Alignment;
                    _dgsum.Columns.Add(dgsumc);
                }
                _dg.AllowUserToAddRows = false;
                _dg.RowHeadersVisible = false;
                _dg.ReadOnly = false;
                _dg.CellValidating += dataGridView1_CellValidating;
                _dg.ScrollBars = ScrollBars.Vertical;
                _dgsum.RowHeadersVisible = false;
                _dgsum.AllowUserToAddRows = false;
                _dgsum.Top = _dg.Top + _dg.Height;
                _dgsum.Left = _dg.Left;
                _dgsum.Width = _dg.Width;
                _dgsum.RowHeadersVisible = false;
                _dgsum.ColumnHeadersHeight = 30;
                if (itotalwidth > grid.iWidth)
                {
                    _dgsum.Height = 50;
                }
                else { _dgsum.Height = 30; }
                _dgsum.ScrollBars = ScrollBars.Horizontal;
                _dgsum.Scroll += dataGridViewSum_Scroll;
                _dgsum.AllowUserToAddRows = false;
                main.Controls.Add(_dg);
                main.Controls.Add(_dgsum);
            }
            #endregion
        }


        #region 合计滚动，数据跟着滚动
        private void dataGridViewSum_Scroll(object sender, ScrollEventArgs e)
        {
            if (e.ScrollOrientation == ScrollOrientation.HorizontalScroll)
            {
                _dg.FirstDisplayedScrollingColumnIndex = _dgsum.FirstDisplayedScrollingColumnIndex;
            }
        }
        #endregion


        #region 数据验证
        private void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
        {
            sumcol(e.ColumnIndex);
        }
        #endregion

        #region 计算所有列合计
        /// <summary>
        /// 计算所有列合计
        /// </summary>
        public void sumcolAll()
        {
            for (int i = 0; i < _dg.Columns.Count; i++)
            { sumcol(i); }
        }

        #region 计算某列合计
        /// <summary>
        /// 计算某列合计
        /// </summary>
        /// <param name="icol"></param>
        public void sumcol(int icol)
        {
            var dgc = _dg.Columns[icol];
            var colname = dgc.Name;
            var t = _vouchs.First(s => s.FieldCode == colname);
            if (t != null)
            {
                if (t.FootCount.ObjToString().Length > 0)
                {
                    decimal sum = 0;
                    for (int i = 0; i < _dg.Rows.Count; i++)
                    {
                        sum += _dg.Rows[i].Cells[icol].Value.ObjToDecimal();
                    }
                    _dgsum.Columns[icol].HeaderText = sum.ToString(t.cFormat);
                }
            }
        }
        #endregion

        #endregion



        #endregion


    }
}
